package com.android.manghe.member.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.common.activity.PayFailActivity
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.events.RefreshMemberInfoEvent
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.member.presenter.PBuyMember
import com.android.manghe.quickpay.activity.QuickPayDetailActivity
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes
import com.android.manghe.common.webview.ERefreshWebType
import com.android.manghe.common.webview.WebViewActivity
import com.android.manghe.common.webview.WebViewParameter
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.android.manghe.view.dialog.ExistBuyMemberDialog
import com.eightbitlab.rxbus.Bus
import kotlinx.android.synthetic.main.activity_buy_member.*
import kotlinx.android.synthetic.main.activity_buy_member.btnConfirmPay
import kotlinx.android.synthetic.main.activity_buy_member.ivClosePay
import kotlinx.android.synthetic.main.activity_buy_member.layoutAgreement
import kotlinx.android.synthetic.main.activity_buy_member.layoutPay
import kotlinx.android.synthetic.main.activity_buy_member.paymentRecyclerView
import kotlinx.android.synthetic.main.activity_buy_member.tvPay
import kotlinx.android.synthetic.main.activity_buy_member.tvPrice

class BuyMemberActivity : MVPActivity<PBuyMember>() {
    private var isCheck = false
    private var mPaymentAdapter: PaymentAdapter? = null

    override fun getLayoutId(): Int = R.layout.activity_buy_member

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("会员中心").setTitleAndStatusBgColor(R.color.white)
            .setLeftIcon(R.mipmap.icon_back_black) {
                showExitDialog()
            }

        paymentRecyclerView.layoutManager =
            AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mPaymentAdapter = PaymentAdapter(this, ArrayList<PaymentTypeRes.DataBean.PaymentBean>())
        paymentRecyclerView.addItemDecoration(
            RecyclerViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL
            )
        )
        paymentRecyclerView.adapter = mPaymentAdapter
        initListener()
        p.loadMemberCardDetail()
        p.getPaymentType()
    }

    fun setViewData(price: String) {
        tvPrice.text = "$price"
    }

    private fun showExitDialog() {
        ExistBuyMemberDialog(this, object : ExistBuyMemberDialog.IExistBuyMemberDialogCallback {
            override fun giveUp() {
                finish()
            }

            override fun continuePay() {
                tvPay.performClick()
            }

        }).show()
    }

    fun initListener() {
        ivCheck.setOnClickListener {
            isCheck = !isCheck
            ivCheck.setImageResource(if (isCheck) R.mipmap.tick_click_black else R.mipmap.tick_normal)
        }
        tvAgreement.setOnClickListener {
            WebViewActivity.showActivity(
                mContext, WebViewParameter.WebParameterBuilder()
                    .setUrl("https://www.youtu888.com/protocol/member_agreement.html")
                    .setShowProgress(true)
                    .setCanHistoryGoBackOrForward(true)
                    .setReloadable(true)
                    .setReloadType(ERefreshWebType.ClickRefresh)
                    .setCustomTitle("会员协议")
                    .build()
            )
//            open(AgreementActivity::class.java, hashMapOf<String,Any>("type" to 2))
        }
        tvPay.setOnClickListener {
            if (!isCheck) {
                ToastUtil.showLong(this, "请先勾选《会员协议》")
                val shake: Animation = AnimationUtils.loadAnimation(
                    applicationContext, R.anim.shake
                )
                layoutAgreement.startAnimation(shake)
                return@setOnClickListener
            }
            layoutPay.visibility = View.VISIBLE
        }

        btnConfirmPay.setOnClickListener {
            if (p.couponBean != null &&!mPaymentAdapter?.selectedPayment?.pay_id.isNullOrEmpty()
                && !mPaymentAdapter?.selectedPayment?.pay_code.isNullOrEmpty()) {
                layoutPay.visibility = View.GONE
                p.getOrderMsg(
                    p.couponBean.id,
                    mPaymentAdapter?.selectedPayment?.pay_id,
                    mPaymentAdapter?.selectedPayment?.pay_code
                )
            } else {
                ToastUtil.showLong(this, "请检查您的网络后重新进入该界面")
            }
        }
        ivClosePay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
        layoutPay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
        mPaymentAdapter?.setOnItemClickListener { adapter, view, position ->
            mPaymentAdapter?.selectedItem(adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean)
        }
    }

    override fun onBackPressed() {
        when (layoutPay.visibility) {
            View.VISIBLE -> {
                layoutPay.visibility = View.GONE
            }
            View.GONE -> {
                showExitDialog()
            }
            else -> {
                tvPay.performClick()
            }
        }
    }

    fun updatePayments(paymentList: List<PaymentTypeRes.DataBean.PaymentBean>) {

        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        try {
            val lp = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                paymentList.size * DisplayUtil.dip2px(this, 60f)
            )
            lp.topMargin = DisplayUtil.dip2px(this, 20f)
            lp.bottomMargin = DisplayUtil.dip2px(this, 20f)
            paymentRecyclerView.layoutParams = lp
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


    fun payFail() {
        ToastUtil.showShort(this, "未完成支付")
    }

    fun paySuccess() {
        finish()
        open(PaySuccessActivity::class.java)
        Bus.send(RefreshMemberInfoEvent())
    }

    fun toPayByH5(url: String) {
        SimpleWebViewActivity.showActivity(this, url, "支付")
    }

    fun toPayByBrowser(url: String, orderId: String) {
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog =
                ConfirmPayResultDialog(this, orderId, object : ConfirmPayResultDialog.CallBack {
                    override fun callBack(orderId: String) {
                        //支付成功
                        Bus.send(RefreshMemberInfoEvent())
                    }
                })
            dialog.show()
        }
    }

    fun openQuickPay(buyMemberShangMengZhiFuData: BuyMemberShangMengZhiFuRes.DataBean) {
        open(
            QuickPayDetailActivity::class.java,
            mapOf("buyMemberShangMengZhiFuData" to buyMemberShangMengZhiFuData),
            2000
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.extras != null && data.extras.getBoolean("fail", false)) {
                finish()
                open(PayFailActivity::class.java)
                Bus.send(RefreshMemberInfoEvent())
                return
            }
            if (requestCode == 1000 || requestCode == 2000) {
                if (data != null  && data.extras != null && data.extras.getBoolean("fail", false)) {
                    finish()
                    open(PayFailActivity::class.java)
                    Bus.send(RefreshMemberInfoEvent())
                    return
                }
                //翼支付、快捷支付 成功支付
                finish()
                open(PaySuccessActivity::class.java)
                Bus.send(RefreshMemberInfoEvent())
            }
        }
    }
}